package com.stadium.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.stadium.bean.User;
import com.stadium.servlet.UserServlet;

public class LoginRealm extends AuthorizingRealm {
	
	@Autowired
	private UserServlet userServlet;

	//认证
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String account = (String) principals.getPrimaryPrincipal();
		
		User user = userServlet.getByAccount(account);
		Integer role = user.getRole();
		SimpleAuthorizationInfo info = null;
		if(role != null){
			 info = new SimpleAuthorizationInfo();
			 if(role.equals(0)){
				 info.addRole("user");
			 } else if(role.equals(1)){
				 info.addRole("eventManager");
			 } else if(role.equals(2)){
				 info.addRole("equipManager");
			 } else if(role.equals(3)){
				 info.addRole("siteManager");
			 } else if(role.equals(4)){
				 info.addRole("admin");
			 }
		}
	
		return info;
	}

	
	//授权
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		
		String account = (String) token.getPrincipal();
		User user = userServlet.getByAccount(account);
		session.setAttribute("user", user);
		System.out.println("账号：" + user.getAccount() + "名字:" +user.getUsername());
		//密码加密
		String password = user.getPassword();
		ByteSource credentialsSalt = ByteSource.Util.bytes(account);
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(account, password, credentialsSalt , getName());
		
		return info;
	}

}
